package com.yyx_yu.demo.demo;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private  FrameLayout frameLayout;
    private static HashMap<String,View> map = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(this);
        frameLayout = (FrameLayout) findViewById(R.id.frameLayout_view1);

        onNavigationItemSelected(bottomNavigationView.getMenu().getItem(0));
    }



    private void addView(String url){

        if(frameLayout == null){
            return;
        }

        frameLayout.removeAllViews();

        if(map.get(url) ==  null) {
            WebView webView = new WebView(this);
            webView.loadUrl(url);

            webView.setWebViewClient(new WebViewClient(){
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }
            });

            map.put(url,webView);
        }

        Toast.makeText(this,url,Toast.LENGTH_SHORT);

        FrameLayout.LayoutParams fllp =  new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);
        frameLayout.addView(map.get(url),fllp);

    }


    /**
     * Called when an item in the bottom navigation menu is selected.
     *
     * @param item The selected item
     * @return true to display the item as the selected item and false if the item should not
     * be selected. Consider setting non-selectable items as disabled preemptively to
     * make them appear non-interactive.
     */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){
            case R.id.action_search:
                addView("http://baidu.com");
                break;
            case R.id.action_settings:
                addView("http://qq.com");
                break;
            case R.id.action_navigation:
                addView("http://jd.com");
                break;
            default:
                addView("http://www.deppon.com");
                break;
        }

        return true;
    }
}
